import {
  modelOptions,
  Prop,
  plugin,
  index,
  getModelForClass,
  ReturnModelType
} from '@typegoose/typegoose';
import { AutoIncrementID } from '@typegoose/auto-increment';
import { ApiProperty, OmitType, PartialType } from '@nestjs/swagger';

// 使用AutoIncrementID插件，设置userId字段自增，从1开始
@plugin(AutoIncrementID, { field: 'menuId', startAt: 1 })
// 创建索引，username字段唯一
@index({ name: 1 }, { unique: true })
@modelOptions({
  schemaOptions: {
    //数据库集合的名称
    collection: 'menu',
    //数据库创建及修改时间自动完善填充
    timestamps: true
  }
})
export class Menu {
  @Prop()
  readonly menuId: number;

  @ApiProperty({
    description: '菜单名称',
    type: String,
    example: '系统管理',
    required: true
  })
  @Prop({ required: true, trim: true })
  name: string;

  @ApiProperty({
    description: '菜单层级类型',
    type: Number,
    example: 1
  })
  @Prop()
  type?: number;

  @ApiProperty({
    description: '菜单路径',
    type: String,
    example: 'main/system'
  })
  @Prop()
  url?: string;

  @ApiProperty({
    description: '图标',
    type: String,
    example: 'el-icon-setting'
  })
  @Prop()
  icon?: string;

  @ApiProperty({
    description: '菜单权限',
    type: String,
    example: 'system:user:create'
  })
  @Prop()
  permission?: string;

  @ApiProperty({ description: '父级菜单id', type: String, example: 1 })
  @Prop()
  parentId?: string;

  @ApiProperty({ description: '父级菜单id', type: [Menu] })
  @Prop({ ref: 'Menu', localField: 'parentId', foreignField: 'menuId' })
  children?: Menu[];
}

// 导出UserModel，用于获取User模型
export const menuModel = getModelForClass(Menu);

// 定义UserModelType，用于返回User模型的类型
export type menuModelReturnType = ReturnModelType<typeof Menu>;

export class CreateMenuDto extends OmitType(Menu, [
  'menuId',
  'children'
] as const) {}
export class UpdateMenuDto extends PartialType(CreateMenuDto) {}
